package com.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.pojo.common.PageResult;
import com.crm.pojo.common.Result;
import com.crm.pojo.domain.Course;
import com.crm.pojo.dto.CourseCreateDto;
import com.crm.pojo.dto.CourseQueryDto;
import com.crm.pojo.vo.CourseVo;
import com.crm.service.CourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程管理控制器
 */
@RestController
@RequestMapping("/clues/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    /**
     * 根据ID获取课程信息（用于编辑回显）
     *
     * @param id 课程ID
     * @return 课程信息
     */
    @GetMapping("/{id}")
    public Result getCourseById(@PathVariable Integer id) {
        try {
            if (id == null) {
                return Result.fail("课程ID不能为空");
            }
            
            Course course = courseService.getById(id);
            if (course == null) {
                return Result.fail("未找到指定课程");
            }
            return Result.success(course);
        } catch (Exception e) {
            return Result.fail("获取课程信息失败: " + e.getMessage());
        }
    }

    /**
     * 课程搜索
     *
     * @param queryDto 查询参数
     * @return 课程列表
     */
    @GetMapping("/list")
    public PageResult<CourseVo, Object> list(CourseQueryDto queryDto) {
        try {
            // 设置默认分页参数
            if (queryDto.getPageNum() == null || queryDto.getPageNum() <= 0) {
                queryDto.setPageNum(1);
            }
            if (queryDto.getPageSize() == null || queryDto.getPageSize() <= 0) {
                queryDto.setPageSize(10);
            }

            Page<Course> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
            LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();

            // 使用工具方法构建查询条件
            buildQueryConditions(queryDto, queryWrapper);

            // 按创建时间倒序排列
            queryWrapper.orderByDesc(Course::getCreateTime);

            // 执行分页查询
            Page<Course> result = courseService.page(page, queryWrapper);

            // 转换为VO对象
            List<CourseVo> voList = result.getRecords().stream().map(course -> {
                CourseVo vo = new CourseVo();
                BeanUtils.copyProperties(course, vo);
                return vo;
            }).collect(Collectors.toList());

            // 返回结果
            PageResult<CourseVo, Object> pageResult = new PageResult<>();
            pageResult.setTotal(result.getTotal());
            pageResult.setRows(voList);
            pageResult.setCode(200);
            pageResult.setMsg("查询成功");
            return pageResult;
        } catch (Exception e) {
            // 错误处理
            PageResult<CourseVo, Object> errorResult = new PageResult<>();
            errorResult.setCode(500);
            errorResult.setMsg("查询失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 合同页面搜索获取课程下拉列表
     *
     * @return
     */
    @GetMapping("/listselect")
    public Result listSelect() {
        List<Course> list = courseService.list();
        return Result.success(list);
    }

    /**
     * 添加课程
     *
     * @param courseCreateDto 课程信息
     * @return 添加结果
     */
    @PostMapping
    public Result addCourse(@RequestBody CourseCreateDto courseCreateDto) {
        try {
            // 参数校验
            StringBuilder errorMsg = new StringBuilder();

            // 校验课程学科
            if (!StringUtils.hasText(courseCreateDto.getSubject())) {
                errorMsg.append("课程学科不能为空；");
            }

            // 校验课程名称 (1-10字)
            if (!StringUtils.hasText(courseCreateDto.getName())) {
                errorMsg.append("课程名称不能为空；");
            } else if (courseCreateDto.getName().length() < 1 || courseCreateDto.getName().length() > 10) {
                errorMsg.append("课程名称长度必须在1-10个字符之间；");
            }

            // 校验适用人群
            if (!StringUtils.hasText(courseCreateDto.getApplicablePerson())) {
                errorMsg.append("适用人群不能为空；");
            }

            // 校验课程价格 (1-5位整数)
            if (courseCreateDto.getPrice() == null) {
                errorMsg.append("课程价格不能为空；");
            } else if (courseCreateDto.getPrice().compareTo(BigDecimal.valueOf(99999)) > 0 ||
                    courseCreateDto.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                errorMsg.append("课程价格必须是1-5位正整数；");
            }

            // 校验课程介绍 (0-20字)
            if (courseCreateDto.getInfo() != null && courseCreateDto.getInfo().length() > 20) {
                errorMsg.append("课程介绍长度不能超过20个字符；");
            }

            // 如果有错误信息，返回错误
            if (errorMsg.length() > 0) {
                Result result = new Result();
                result.setCode(400);
                result.setMessage(errorMsg.toString());
                return result;
            }

            // 转换DTO到实体类
            Course course = new Course();
            course.setSubject(courseCreateDto.getSubject());
            course.setName(courseCreateDto.getName());
            course.setApplicablePerson(courseCreateDto.getApplicablePerson());
            course.setPrice(courseCreateDto.getPrice());
            course.setInfo(courseCreateDto.getInfo());

            // 设置创建时间
            course.setCreateTime(new Date());

            // 生成8位课程编号 (字母+数字)
            String code = generateCourseCode();
            course.setCode(code);

            // 保存课程
            boolean saved = courseService.save(course);

            if (saved) {
                Result result = new Result();
                result.setCode(200);
                result.setMessage("操作成功");
                return result;
            } else {
                Result result = new Result();
                result.setCode(500);
                result.setMessage("操作失败");
                return result;
            }
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(500);
            result.setMessage("操作失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 生成8位课程编号 (字母+数字)
     *
     * @return 课程编号
     */
    private String generateCourseCode() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int index = (int) (Math.random() * chars.length());
            code.append(chars.charAt(index));
        }
        return code.toString();
    }

    /**
     * 更新课程信息
     *
     * @param course 课程信息
     * @return 更新结果
     */
    @PutMapping
    public Result updateCourse(@RequestBody Course course) {
        try {
            // 设置更新时间
            course.setUpdateTime(new Date());

            // 更新课程
            boolean updated = courseService.updateById(course);

            if (updated) {
                Result result = new Result();
                result.setCode(200);
                result.setMessage("操作成功");
                return result;
            } else {
                Result result = new Result();
                result.setCode(500);
                result.setMessage("操作失败");
                return result;
            }
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(500);
            result.setMessage("操作失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除课程
     *
     * @param id 课程ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result deleteCourse(@PathVariable String id) {
        try {
            // 将String类型的ID转换为Integer
            Integer courseId = Integer.valueOf(id);

            boolean removed = courseService.removeById(courseId);

            if (removed) {
                Result result = new Result();
                result.setCode(200);
                result.setMessage("操作成功");
                return result;
            } else {
                Result result = new Result();
                result.setCode(500);
                result.setMessage("操作失败");
                return result;
            }
        } catch (Exception e) {
            Result result = new Result();
            result.setCode(500);
            result.setMessage("操作失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 构建查询条件
     *
     * @param queryDto     查询参数
     * @param queryWrapper 查询条件
     */
    private void buildQueryConditions(CourseQueryDto queryDto, LambdaQueryWrapper<Course> queryWrapper) {
        // 课程编号查询
        if (StringUtils.hasText(queryDto.getCode())) {
            queryWrapper.like(Course::getCode, queryDto.getCode());
        }

        // 课程名称查询
        if (StringUtils.hasText(queryDto.getName())) {
            queryWrapper.like(Course::getName, queryDto.getName());
        }

        // 适用人群查询
        if (StringUtils.hasText(queryDto.getApplicablePerson())) {
            queryWrapper.eq(Course::getApplicablePerson, queryDto.getApplicablePerson());
        }

        // 课程学科查询
        if (StringUtils.hasText(queryDto.getSubject())) {
            queryWrapper.eq(Course::getSubject, queryDto.getSubject());
        }

        // 创建时间范围查询
        if (queryDto.getBeginCreateTime() != null) {
            queryWrapper.ge(Course::getCreateTime, queryDto.getBeginCreateTime());
        }
        if (queryDto.getEndCreateTime() != null) {
            queryWrapper.le(Course::getCreateTime, queryDto.getEndCreateTime());
        }
    }
}